<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="在群里有人发了个搞笑图片，图片上包含这两个题目 12[] + &amp;#123;&amp;#125; &#x2F;* [object Object] *&#x2F;&amp;#123;&amp;#125; + [] &#x2F;* 0&#x2F;  好像记得为什么这么输出原因，自己推又忘了原因（第2个有点看不懂了），于是决定查找资料，复习一下JavaScript的类型转换">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript类型转换">
<meta property="og:url" content="https://hxy1997.xyz/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="在群里有人发了个搞笑图片，图片上包含这两个题目 12[] + &amp;#123;&amp;#125; &#x2F;* [object Object] *&#x2F;&amp;#123;&amp;#125; + [] &#x2F;* 0&#x2F;  好像记得为什么这么输出原因，自己推又忘了原因（第2个有点看不懂了），于是决定查找资料，复习一下JavaScript的类型转换">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202828.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202901.webp">
<meta property="article:published_time" content="2021-04-05T11:20:00.000Z">
<meta property="article:modified_time" content="2021-07-24T09:39:13.202Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="数据类型">
<meta property="article:tag" content="类型转换">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202828.png">

<link rel="canonical" href="https://hxy1997.xyz/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>JavaScript类型转换 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JavaScript类型转换
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-05 19:20:00" itemprop="dateCreated datePublished" datetime="2021-04-05T19:20:00+08:00">2021-04-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-07-24 17:39:13" itemprop="dateModified" datetime="2021-07-24T17:39:13+08:00">2021-07-24</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在群里有人发了个搞笑图片，图片上包含这两个题目</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[] + &#123;&#125; <span class="comment">/* [object Object] */</span></span><br><span class="line">&#123;&#125; + [] <span class="comment">/* 0/</span></span><br></pre></td></tr></table></figure>

<p>好像记得为什么这么输出原因，自己推又忘了原因（第2个有点看不懂了），于是决定查找资料，复习一下JavaScript的类型转换</p>
<span id="more"></span>

<h3 id="1-和"><a href="#1-和" class="headerlink" title="1.[] + {}和{} + []"></a>1.[] + {}和{} + []</h3><ol>
<li>number + number</li>
<li>string + string</li>
</ol>
<p>所以，在JavaScript隐式转换规则中首先会推算两个操作数是不是number类型，如果是则直接运算得出结果。<br>如果有一个数为string，则将另一个操作数隐式的转换为string，然后通过字符串拼接得出结果。<br>如果为布尔值这种简单的数据类型，那么将会转换为number类型来进行运算得出结果。<br>如果操作数为对象或者是数组这种复杂的数据类型，那么就将两个操作数都转换为字符串，进行拼接 。</p>
<p>在题目中</p>
<p>[] + {} 中，[]会通过隐式转换规则，调用toString方法转换为 “” ，同理{}转换为[object Object], 相加得出字符串拼接结果 [object Object]</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> <span class="built_in">Array</span>;</span><br><span class="line">arr.toString() <span class="comment">// &quot;&quot;</span></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>;</span><br><span class="line">obj.toString() <span class="comment">// &quot;[object Object]&quot;</span></span><br></pre></td></tr></table></figure>

<p>而 {} + []为什么结果会是0呢？<br>在js中{}代表复合语句，在一些js解释器会将开头的 {} 看作一个代码块，而不是一个Object（在es6以前只有函数作用域与全局作用域，还没有块级作用域）而这里的{}只是空符号，不表明任何意思。这里的+[]是一个隐式转换，所以参与运算的只有+[]，在这里将[]转换成了number类型，所以得出结果为0。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#125; + []; <span class="comment">// [].toString() == &quot;&quot;;  +&quot;&quot; == 0</span></span><br></pre></td></tr></table></figure>

<h3 id="2-类型转换的分类"><a href="#2-类型转换的分类" class="headerlink" title="2.类型转换的分类"></a>2.类型转换的分类</h3><p>按照转换方式分类，将值从一种类型转换成另一种类型，有两种情况，显示强制类型转换和隐式强制类型转换。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">66</span>;</span><br><span class="line"><span class="keyword">var</span> b = a + <span class="string">&#x27;&#x27;</span>; <span class="comment">// 隐式强制类型转换</span></span><br><span class="line"><span class="keyword">var</span> c = <span class="built_in">String</span>(a); <span class="comment">// 显式强制类型转换</span></span><br></pre></td></tr></table></figure>

<p>按照转换目标分，在 <code>JS</code> 中类型转换有三种情况，分别是：</p>
<ul>
<li>转换为布尔值</li>
<li>转换为数字</li>
<li>转换为字符串</li>
</ul>
<h3 id="3-详细的类型转换结果"><a href="#3-详细的类型转换结果" class="headerlink" title="3.详细的类型转换结果"></a>3.详细的类型转换结果</h3><p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202828.png"></p>
<h4 id="3-1-ToString：-非字符串到字符串的强制类型转换。String-value"><a href="#3-1-ToString：-非字符串到字符串的强制类型转换。String-value" class="headerlink" title="3.1 ToString： 非字符串到字符串的强制类型转换。String(value)"></a>3.1 ToString： 非字符串到字符串的强制类型转换。<code>String(value)</code></h4><p>基本类型值的字符串化规则：</p>
<table>
<thead>
<tr>
<th align="center">值类型</th>
<th align="center">转换规则</th>
</tr>
</thead>
<tbody><tr>
<td align="center">null</td>
<td align="center"><code>&quot;null&quot;</code></td>
</tr>
<tr>
<td align="center">undefined</td>
<td align="center"><code>&quot;undefined&quot;</code></td>
</tr>
<tr>
<td align="center">true</td>
<td align="center"><code>&quot;true&quot;</code></td>
</tr>
<tr>
<td align="center">[]</td>
<td align="center"><code>&quot;&quot;</code></td>
</tr>
<tr>
<td align="center">普通对象</td>
<td align="center"><code>&quot;[object Object]&quot;</code></td>
</tr>
<tr>
<td align="center">极小和极大的数字</td>
<td align="center">指数形式</td>
</tr>
</tbody></table>
<p>如果对象有自己的 toString() 方法，字符串化时就会调用该方法并使用其返回值；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">a.toString(); <span class="comment">// &quot;1,2,3&quot;</span></span><br></pre></td></tr></table></figure>

<h5 id="JSON-字符串化"><a href="#JSON-字符串化" class="headerlink" title="JSON 字符串化"></a>JSON 字符串化</h5><p>对大多数简单的值都可以使用<code>JSON.stingify(...)</code>字符串化。<br> JSON.stringify(..) 在对象中遇到 undefined、function 和 symbol 时会自动将其忽略，在数组中则会返回 null</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = &#123;</span><br><span class="line">    name: <span class="string">&#x27;Tina&#x27;</span>,</span><br><span class="line">    age: <span class="number">20</span>,</span><br><span class="line">    sayHi: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        alert(<span class="string">&#x27;Hi&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    height: <span class="literal">null</span>,</span><br><span class="line">    weight: <span class="literal">undefined</span>,</span><br><span class="line">    hobbies: [</span><br><span class="line">        <span class="string">&#x27;swimming&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;reading&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;singing&#x27;</span>,</span><br><span class="line">        <span class="literal">null</span>,</span><br><span class="line">        <span class="literal">undefined</span>,</span><br><span class="line">        <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;hobbies&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">JSON</span>.stringify(a);</span><br><span class="line"><span class="comment">// &quot;&#123;&quot;name&quot;: &quot;Tina&quot;, &quot;age&quot;: 20, &quot;height&quot;: null, &quot;hobbies&quot;: [&quot;swimming&quot;, &quot;reading&quot;, &quot;singing&quot;, null, null, null]&#125;&quot;</span></span><br></pre></td></tr></table></figure>

<p>如果要对含有非法 JSON 值的对象做字符串化，或者对象中的某些值无法被序列化时，就需要定义 toJSON() 方法来返回一个安全的 JSON 值。<br> 如果对象中定义了 toJSON() 方法，JSON 字符串化时会首先调用该方法，然后用它的返回值来进行序列化。</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202901.webp" alt="img"></p>
<p>图中循环引用会产生错误</p>
<p> toJSON() 是返回一个能够被字符串化的安全的 JSON 值。</p>
<h5 id="JSON-stringify-value-replacer-space"><a href="#JSON-stringify-value-replacer-space" class="headerlink" title="JSON.stringify(value[, replacer [, space]])"></a><code>JSON.stringify(value[, replacer [, space]])</code></h5><p>replacer表示要字符化的属性<br> space用于美化输出</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = &#123;<span class="attr">b</span>: <span class="number">1</span>, <span class="attr">c</span>: <span class="number">2</span>, <span class="attr">d</span>: <span class="number">3</span>&#125;;</span><br><span class="line"><span class="built_in">JSON</span>.stringify(a, [<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;d&#x27;</span>]); <span class="comment">//  &quot;&#123;&quot;b&quot;:1,&quot;d&quot;:3&#125;&quot;</span></span><br></pre></td></tr></table></figure>

<h4 id="3-2-ToNumber：-非数字值到数字值-Number-value"><a href="#3-2-ToNumber：-非数字值到数字值-Number-value" class="headerlink" title="3.2 ToNumber： 非数字值到数字值 Number(value)"></a>3.2 ToNumber： 非数字值到数字值 <code>Number(value)</code></h4><p>非数字值到数字值转化规则：</p>
<table>
<thead>
<tr>
<th align="center">值类型</th>
<th align="center">转换规则</th>
</tr>
</thead>
<tbody><tr>
<td align="center">null</td>
<td align="center">0</td>
</tr>
<tr>
<td align="center">undefined</td>
<td align="center">undefined</td>
</tr>
<tr>
<td align="center">true</td>
<td align="center">1</td>
</tr>
<tr>
<td align="center">false, null</td>
<td align="center">0</td>
</tr>
<tr>
<td align="center">转换出错</td>
<td align="center">NaN</td>
</tr>
</tbody></table>
<h4 id="3-3-ToBoolean-转换为布尔类型-Boolean-value"><a href="#3-3-ToBoolean-转换为布尔类型-Boolean-value" class="headerlink" title="3.3 ToBoolean: 转换为布尔类型 Boolean(value)"></a>3.3 ToBoolean: 转换为布尔类型 <code>Boolean(value)</code></h4><p>JavaScript 中的值可以分为以下两类：<br> (1) 可以被强制类型转换为 false 的值<br> (2) 其他（被强制类型转换为 true 的值）</p>
<h5 id="假值："><a href="#假值：" class="headerlink" title="假值："></a>假值：</h5><ul>
<li>undefined</li>
<li>+0, -0, NaN</li>
<li>false</li>
<li>null</li>
<li>“”</li>
</ul>
<h5 id="假值对象"><a href="#假值对象" class="headerlink" title="假值对象"></a>假值对象</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="keyword">new</span> <span class="built_in">Boolean</span>(<span class="literal">false</span>);</span><br><span class="line"><span class="keyword">var</span> b = <span class="keyword">new</span> <span class="built_in">Number</span>(<span class="number">0</span>);</span><br><span class="line"><span class="keyword">var</span> c = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">&quot;&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>虽然 JavaScript 代码中会出现假值对象，但它实际上并不属于 JavaScript 语<br> 言的范畴。</p>
<h5 id="真值"><a href="#真值" class="headerlink" title="真值"></a>真值</h5><p>假值列表之外的值</p>
<h3 id="4-强制类型转换"><a href="#4-强制类型转换" class="headerlink" title="4. 强制类型转换"></a>4. 强制类型转换</h3><h4 id="4-1-字符串和数字之间的显式强制类型转换"><a href="#4-1-字符串和数字之间的显式强制类型转换" class="headerlink" title="4.1 字符串和数字之间的显式强制类型转换"></a>4.1 字符串和数字之间的显式强制类型转换</h4><ul>
<li>字符串与数字是通过 String(..) 和 Number(..) 这两个内建函数(比较常用)</li>
<li><code>.toString()</code></li>
<li><code>+</code>（比较少用）</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">42</span>;</span><br><span class="line"><span class="keyword">var</span> b = a.toString();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> c = <span class="string">&#x27;66.6&#x27;</span></span><br><span class="line"><span class="keyword">var</span> d = +c</span><br></pre></td></tr></table></figure>

<p>日期显式转换为数字</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> d = +<span class="keyword">new</span> <span class="built_in">Date</span>; <span class="comment">// 可直接转换为时间戳， 不建议这么用，知道可以这么用就可以了</span></span><br><span class="line"><span class="keyword">var</span> timestamp = <span class="built_in">Date</span>.now();  <span class="comment">// 获取时间戳</span></span><br></pre></td></tr></table></figure>

<p>~运算符, 字位操作“非”</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello world&#x27;</span></span><br><span class="line"><span class="built_in">console</span>.log(~a.indexOf(<span class="string">&#x27;aaa&#x27;</span>)) <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">console</span>.log(~a.indexOf(<span class="string">&#x27;he&#x27;</span>)) <span class="comment">// -1</span></span><br></pre></td></tr></table></figure>

<h4 id="4-2-字符串和数字之间的隐式强制类型转换"><a href="#4-2-字符串和数字之间的隐式强制类型转换" class="headerlink" title="4.2 字符串和数字之间的隐式强制类型转换"></a>4.2 字符串和数字之间的隐式强制类型转换</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = [<span class="number">1</span>,<span class="number">2</span>];</span><br><span class="line"><span class="keyword">var</span> b = [<span class="number">3</span>,<span class="number">4</span>];</span><br><span class="line">a + b; <span class="comment">// &quot;1,23,4&quot;</span></span><br></pre></td></tr></table></figure>

<p>a和b都不是字符串，但是它们都被强制转换成字符串并拼接。<br> 类型转换都做了什么：</p>
<ul>
<li>调用obj[Symbol.toPrimitive] (hint)（如果存在）</li>
<li>预期被转换成字符串类型，尝试toString()和valueOf()，否则退出。</li>
<li>如如果预期被转换成默认类型或者数字类型时，尝试valueOf()和toString()，否则退出。</li>
</ul>
<p>也就是说，如果其中一个操作数是对象（包括数组），则首先对其调用ToPrimitive 抽象操作，该抽象操作再调用 [[DefaultValue]]，以数字作为上下文</p>
<h4 id="4-3-显式解析数字字符串"><a href="#4-3-显式解析数字字符串" class="headerlink" title="4.3 显式解析数字字符串"></a>4.3 显式解析数字字符串</h4><p>解析允许存在非数字的字符，从左到右，遇到非字符就停止<br> 转换不允许存在非数字字符， 否则返回NaN</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&quot;14&quot;</span>;</span><br><span class="line"><span class="built_in">Number</span>(a); <span class="comment">// 14</span></span><br><span class="line"><span class="built_in">parseInt</span>(a); <span class="comment">// 14</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> b = <span class="string">&quot;14px&quot;</span>;</span><br><span class="line"><span class="built_in">Number</span>(b); <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">parseInt</span>(b); <span class="comment">// 14</span></span><br></pre></td></tr></table></figure>

<h4 id="4-4-显式转换为布尔值-Boolean-value"><a href="#4-4-显式转换为布尔值-Boolean-value" class="headerlink" title="4.4 显式转换为布尔值 Boolean(value)"></a>4.4 显式转换为布尔值 <code>Boolean(value)</code></h4><p>常用方法是 <code>!!</code>, 为第二个<code>!</code>会将结果反转回原值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&quot;0&quot;</span>;</span><br><span class="line"><span class="keyword">var</span> b = [];</span><br><span class="line"><span class="keyword">var</span> c = &#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> d = <span class="string">&quot;&quot;</span>;</span><br><span class="line"><span class="keyword">var</span> e = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">var</span> f = <span class="literal">null</span>;</span><br><span class="line"><span class="keyword">var</span> g;</span><br><span class="line"></span><br><span class="line">!!a; <span class="comment">// true</span></span><br><span class="line">!!b; <span class="comment">// true</span></span><br><span class="line">!!c; <span class="comment">// true</span></span><br><span class="line">!!d; <span class="comment">// false</span></span><br><span class="line">!!e; <span class="comment">// false</span></span><br><span class="line">!!f; <span class="comment">// false</span></span><br><span class="line">!!g; <span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h4 id="4-5-布尔值到数字到隐式转换"><a href="#4-5-布尔值到数字到隐式转换" class="headerlink" title="4.5 布尔值到数字到隐式转换"></a>4.5 布尔值到数字到隐式转换</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span> + <span class="literal">false</span>; <span class="comment">// 1</span></span><br><span class="line"><span class="number">1</span> + <span class="literal">true</span>; <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<h4 id="4-6-和-amp-amp"><a href="#4-6-和-amp-amp" class="headerlink" title="4.6 || 和 &amp;&amp;"></a>4.6 || 和 &amp;&amp;</h4><p>&amp;&amp; 和 || 运算符的返回值并不一定是布尔类型，而是两个操作数其中一个的值</p>
<h3 id="5-与-的不同"><a href="#5-与-的不同" class="headerlink" title="5. == 与 ===的不同"></a>5. <code>==</code> 与 <code>===</code>的不同</h3><p><code>==</code> 允许在相等比较中进行强制类型转换，而 <code>===</code> 不允许</p>
<p>== 判断的执行时间会比 === 的执行时间多</p>
<ol>
<li>对于string,number等基础类型，== 和 === 是有区别的<br> 1）不同类型间比较，== 只比较“转化成同一类型后的值”看“值”是否相等，=== 如果类型不同，其结果就是不等<br> 2）同类型比较，直接进行“值”比较，两者结果一样</li>
<li>对于Array,Object等高级类型，== 和 === 是没有区别的<br> 进行“指针地址”比较</li>
<li>基础类型与高级类型，== 和 === 是有区别的<br> 1）对于==，将高级转化为基础类型，进行“值”比较<br> 2）因为类型不同，=== 结果为false<br> === 的比较结果比 == 精准得多</li>
</ol>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a>
              <a href="/tags/%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/" rel="tag"><i class="fa fa-tag"></i> 数据类型</a>
              <a href="/tags/%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" rel="tag"><i class="fa fa-tag"></i> 类型转换</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/04/04/JavaScript%E6%89%8B%E5%86%99ES5%E7%BB%A7%E6%89%BF/" rel="prev" title="JavaScript手写ES5继承">
      <i class="fa fa-chevron-left"></i> JavaScript手写ES5继承
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/" rel="next" title="Typescript速成自学">
      Typescript速成自学 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E5%92%8C"><span class="nav-text">1.[] + {}和{} + []</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E7%9A%84%E5%88%86%E7%B1%BB"><span class="nav-text">2.类型转换的分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E8%AF%A6%E7%BB%86%E7%9A%84%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E7%BB%93%E6%9E%9C"><span class="nav-text">3.详细的类型转换结果</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-ToString%EF%BC%9A-%E9%9D%9E%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%B0%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E3%80%82String-value"><span class="nav-text">3.1 ToString： 非字符串到字符串的强制类型转换。String(value)</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#JSON-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%8C%96"><span class="nav-text">JSON 字符串化</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#JSON-stringify-value-replacer-space"><span class="nav-text">JSON.stringify(value[, replacer [, space]])</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-ToNumber%EF%BC%9A-%E9%9D%9E%E6%95%B0%E5%AD%97%E5%80%BC%E5%88%B0%E6%95%B0%E5%AD%97%E5%80%BC-Number-value"><span class="nav-text">3.2 ToNumber： 非数字值到数字值 Number(value)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-ToBoolean-%E8%BD%AC%E6%8D%A2%E4%B8%BA%E5%B8%83%E5%B0%94%E7%B1%BB%E5%9E%8B-Boolean-value"><span class="nav-text">3.3 ToBoolean: 转换为布尔类型 Boolean(value)</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%81%87%E5%80%BC%EF%BC%9A"><span class="nav-text">假值：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%81%87%E5%80%BC%E5%AF%B9%E8%B1%A1"><span class="nav-text">假值对象</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E7%9C%9F%E5%80%BC"><span class="nav-text">真值</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-text">4. 强制类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%92%8C%E6%95%B0%E5%AD%97%E4%B9%8B%E9%97%B4%E7%9A%84%E6%98%BE%E5%BC%8F%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-text">4.1 字符串和数字之间的显式强制类型转换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%92%8C%E6%95%B0%E5%AD%97%E4%B9%8B%E9%97%B4%E7%9A%84%E9%9A%90%E5%BC%8F%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-text">4.2 字符串和数字之间的隐式强制类型转换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-%E6%98%BE%E5%BC%8F%E8%A7%A3%E6%9E%90%E6%95%B0%E5%AD%97%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-text">4.3 显式解析数字字符串</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-4-%E6%98%BE%E5%BC%8F%E8%BD%AC%E6%8D%A2%E4%B8%BA%E5%B8%83%E5%B0%94%E5%80%BC-Boolean-value"><span class="nav-text">4.4 显式转换为布尔值 Boolean(value)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-5-%E5%B8%83%E5%B0%94%E5%80%BC%E5%88%B0%E6%95%B0%E5%AD%97%E5%88%B0%E9%9A%90%E5%BC%8F%E8%BD%AC%E6%8D%A2"><span class="nav-text">4.5 布尔值到数字到隐式转换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-%E5%92%8C-amp-amp"><span class="nav-text">4.6 || 和 &amp;&amp;</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E4%B8%8E-%E7%9A%84%E4%B8%8D%E5%90%8C"><span class="nav-text">5. &#x3D;&#x3D; 与 &#x3D;&#x3D;&#x3D;的不同</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
